package com.mayisoftware.mayioa.business.input.impl.task;


import com.mayisoftware.mayioa.business.human.api.service.humanmanager.IHumanUploadService;
import com.mayisoftware.mayioa.business.input.api.domain.UploadRecord;
import com.mayisoftware.mayioa.business.input.api.service.IUploadRecordService;
import com.mayisoftware.mayioa.common.impl.utils.*;
import com.mayisoftware.mayioa.platform.api.domain.SysDictData;
import com.mayisoftware.mayioa.platform.api.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * 定时任务调度计划解析
 *
 *
 */
@Component("humanParseTask")
public class HumanParseTask
{
    /**
     * 日志对象
     */
    private static final Logger log = LoggerFactory.getLogger(HumanParseTask.class);

    /**
     * 系统配置服务
     */
//    @Autowired
//    private  ISysConfigService sysConfigService;
    /**
     * 密码服务
     */
//    @Autowired
//    private SysPasswordService passwordService;
    /**
     * 骨干池管理服务
     */
//    @Autowired
//    private IPoolManualService poolManualService;

    /**
     * 报名信息服务
     */
//    @Autowired
//    private IPersonalSignService personSignService;

    /**
     * 打分服务信息
//     */
//    @Autowired
//    private IScoreInfoService scoreInfoService;

    /**
     * 计划配置服务
     */
//    @Autowired
//    private IPlanConfigService planConfigService;

    /**
     * 计划详情服务
     */
//    @Autowired
//    private IPlanConfigDetailService planConfigDetailService;


    /**
     * 职位查询服务
     */
//    @Autowired
//    private ISysPostService sysPostService;

    /**
     * 部门查询服务
     */
//    @Autowired
//    private ISysDeptService deptService;

    /**
     * 数据字典查询服务
     */
    @Autowired
    private ISysDictDataService sysDictDataService;
    /**
     * 上传记录操作服务
     */
    @Autowired
    private IUploadRecordService uploadRecordService;

    @Autowired
    private IHumanUploadService humanUploadService;

    /**
     * 用户管理服务
     */
    @Autowired
    private ISysUserService sysUserService;

    public void parseHumanFiles()
    {
        log.info("开始执行文件解析");

        try {
            //查询数据库记录
            List<UploadRecord> uploadRecords = uploadRecordService.queryRecordListNeedParse();

            if(CollectionUtils.isEmpty(uploadRecords)){
                log.warn("没有需要解析的记录");
                return;
            }

            List<SysDictData> achDatas = sysDictDataService.selectDictDataByType("upload_file_type");
            Map<String,BigDecimal> ach_values = new HashMap<>();

            for (SysDictData data:achDatas){
                ach_values.put(data.getDictLabel(),new BigDecimal(data.getDictValue()));
            }

            String errorFilePath = "";
            for (UploadRecord record:uploadRecords){
                boolean isOk = true;
                UploadRecord updateRecord = new UploadRecord();
                try {
                    log.info("处理记录 id: {} 文件:{}",record.getRecordId(),record.getFilePath());
                    String planFilePath = record.getFilePath();

                    File file =new File(planFilePath);
                    if(StringUtils.isEmpty(planFilePath) || !file.exists() || !file.isFile()){
                        log.error("处理记录 id: {} 文件:{}不存在",record.getRecordId(),record.getFilePath());
                        continue;
                    }

                    String fileName= file.getName();
                    String fileDir=file.getParentFile().getAbsolutePath();
                    String fileNameNoExt = fileName.substring(0,fileName.lastIndexOf("."));
                    errorFilePath = fileDir+File.separator+fileNameNoExt+".log";

                    updateRecord.setRecordId(record.getRecordId());
                    //更新DB状态 正在解析
                    updateRecord.setParseStatus("2");

                    uploadRecordService.editInputRecord(updateRecord);

                    isOk = dealOneRecord(record,file);
                    updateRecord.setFileType(record.getFileType());
                }
                catch (Exception e){
                    isOk = false;
                    log.error("处理记录 id: {} 文件:{},异常",record.getRecordId(),record.getFilePath(),e);
                }
                finally {
                    try {
                        if (isOk){
                            log.info("处理记录 id: {} 文件:{},处理成功",record.getRecordId(),record.getFilePath());
                            //更新DB状态 正在解析
                            updateRecord.setParseStatus("3");
                            uploadRecordService.editInputRecord(updateRecord);
                        }
                        else {
                            log.info("处理记录 id: {} 文件:{},处理失败",record.getRecordId(),record.getFilePath());
                            //更新DB状态 正在解析
                            updateRecord.setParseStatus("4");
                            updateRecord.setErrorPath(errorFilePath);
                            uploadRecordService.editInputRecord(updateRecord);
                        }
                    }
                    catch (Exception e){
                        log.info("处理记录状态异常",e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("文件解析解析异常",e);
        }

        log.info("结束文件解析");
//        poolManualService.modifyPoolInfoToCacl();
    }

    private boolean dealOneRecord(UploadRecord record, File file) {

        List<String> contents =null;
        try {
            contents= ExcelReadWriteUtils.readExcelList(file.getAbsolutePath(),0);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        if(contents==null || contents.size()==0){
            return false;
        }

        contents = completeContents(contents);

        String fileType = "";

        if(contents.get(0).startsWith("姓名,性别,身份证号,考核周期")){
            fileType = "0";
        }else if(contents.get(0).startsWith("姓名,性别,身份证号")){
            fileType = "1";
        }else if(contents.get(0).startsWith("员工编号,姓名,证件号码")){
            fileType = "2";
        }else{
            fileType = "3";
        }
        record.setFileType(fileType);
        humanUploadService.importFileInfos(contents,fileType);
        return true;
    }

    private List<String> completeContents(List<String> contents){
        if(contents==null || contents.size()==0){
            return null;
        }

        List<String> retList = new ArrayList<>();
        int colNums = contents.get(0).split(",",-1).length;
        for (String item:contents) {
            int itemColNums = item.split(",",-1).length;
            for(int i = 0; i< (colNums-itemColNums); ++i){
                item+=",";
            }
            retList.add(item);
        }
        return retList;
    }

}
